//
//  CClass.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/8/1.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "CClass.h"
#import "CColor+UIColor.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "Constants.h"
//#import "LoadingView.h"
#import "MainNavBarViewController.h"
#import "AlertWindow.h"
#import "BaseViewController.h"
@interface CClass()


@end
@implementation CClass
+ (BOOL) checkPassword:(NSString *)password{
    return YES;
    int c = 0;
    for(int i = 0; i < [password length]; ++i) {
        int a = [password characterAtIndex:i];
        if (!((a < 58 && a > 47) || (a < 91 && a > 64) || (a < 123 && a > 96))) {
            return false;
        }
        c += (a < 58 ? 1 : 2);
    }
    return c < [password length] * 2 && c > [password length];
}

+ (void) saveCacheData:(NSString *)data key:(NSString *)key{
    NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];
    [setting setObject:data forKey:key];
    [setting synchronize];
}

+ (void) clearCacheData:(id) key{
    if ([key isKindOfClass:[NSString class]]) {
        [self saveCacheData:nil key:key];
    }else if([key isKindOfClass:[NSArray class]]){
        for (id k in key) {
            [self clearCacheData:k];
        }
    }
}

+ (NSString *) getCacheData:(NSString*)key{
    NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];
    return [setting stringForKey:key];
}

+ (void) saveCacheObject:(id)object key:(NSString *)key{
    NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object];
    [setting setObject:data forKey:key];
    [setting synchronize];
}

+ (id) getCacheObject:(NSString *)key{
    NSUserDefaults *setting = [NSUserDefaults standardUserDefaults];
    NSData *data = [setting objectForKey:key];
    return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

+ (BOOL) hasCacheData:(NSString *)key{
    NSString *data = [self getCacheData:key];
    return data != nil && ![data isEqualToString:@""];
}
//将图片保存到本地
+ (void)SaveImageToLocal:(UIImage*)image Keys:(NSString*)key {
    NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
    [preferences setObject:UIImagePNGRepresentation(image) forKey:key];
}
//从本地获取图片
+ (UIImage*)GetImageFromLocal:(NSString*)key {
    NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
    //[preferences persistentDomainForName:LocalPath];
    NSData* imageData = [preferences objectForKey:key];
    UIImage* image;
    if (imageData) {
        image = [UIImage imageWithData:imageData];
    }
    else {
        image= [UIImage imageNamed:@"Ico_home_head"];
    }
    return image;
}
+ (NSString *)base64:(NSString *)str{
    NSData* originData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSString* encodeResult = [originData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    return encodeResult;
}

+ (NSString *)debase64:(NSString *)str{
    NSData *nsdataFromBase64String = [[NSData alloc]
                                      initWithBase64EncodedString:str options:0];
    NSString *result = [[NSString alloc]initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
    return result;
}

+(NSString *)escape:(NSString *)str{
    NSArray *hex = [NSArray arrayWithObjects:
                    @"00",@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"0A",@"0B",@"0C",@"0D",@"0E",@"0F",
                    @"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"1A",@"1B",@"1C",@"1D",@"1E",@"1F",
                    @"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"2A",@"2B",@"2C",@"2D",@"2E",@"2F",
                    @"30",@"31",@"32",@"33",@"34",@"35",@"36",@"37",@"38",@"39",@"3A",@"3B",@"3C",@"3D",@"3E",@"3F",
                    @"40",@"41",@"42",@"43",@"44",@"45",@"46",@"47",@"48",@"49",@"4A",@"4B",@"4C",@"4D",@"4E",@"4F",
                    @"50",@"51",@"52",@"53",@"54",@"55",@"56",@"57",@"58",@"59",@"5A",@"5B",@"5C",@"5D",@"5E",@"5F",
                    @"60",@"61",@"62",@"63",@"64",@"65",@"66",@"67",@"68",@"69",@"6A",@"6B",@"6C",@"6D",@"6E",@"6F",
                    @"70",@"71",@"72",@"73",@"74",@"75",@"76",@"77",@"78",@"79",@"7A",@"7B",@"7C",@"7D",@"7E",@"7F",
                    @"80",@"81",@"82",@"83",@"84",@"85",@"86",@"87",@"88",@"89",@"8A",@"8B",@"8C",@"8D",@"8E",@"8F",
                    @"90",@"91",@"92",@"93",@"94",@"95",@"96",@"97",@"98",@"99",@"9A",@"9B",@"9C",@"9D",@"9E",@"9F",
                    @"A0",@"A1",@"A2",@"A3",@"A4",@"A5",@"A6",@"A7",@"A8",@"A9",@"AA",@"AB",@"AC",@"AD",@"AE",@"AF",
                    @"B0",@"B1",@"B2",@"B3",@"B4",@"B5",@"B6",@"B7",@"B8",@"B9",@"BA",@"BB",@"BC",@"BD",@"BE",@"BF",
                    @"C0",@"C1",@"C2",@"C3",@"C4",@"C5",@"C6",@"C7",@"C8",@"C9",@"CA",@"CB",@"CC",@"CD",@"CE",@"CF",
                    @"D0",@"D1",@"D2",@"D3",@"D4",@"D5",@"D6",@"D7",@"D8",@"D9",@"DA",@"DB",@"DC",@"DD",@"DE",@"DF",
                    @"E0",@"E1",@"E2",@"E3",@"E4",@"E5",@"E6",@"E7",@"E8",@"E9",@"EA",@"EB",@"EC",@"ED",@"EE",@"EF",
                    @"F0",@"F1",@"F2",@"F3",@"F4",@"F5",@"F6",@"F7",@"F8",@"F9",@"FA",@"FB",@"FC",@"FD",@"FE",@"FF", nil];
    NSMutableString *result = [NSMutableString stringWithString:@""];
    NSInteger strLength = str.length;
    for (int i=0; i<strLength; i++) {
        int ch = [str characterAtIndex:i];
        if (ch == ' ')
        {
            [result appendFormat:@"%C",'+'];
        }
        else if ('A' <= ch && ch <= 'Z')
        {
            [result appendFormat:@"%C",(char)ch];
            
        }
        else if ('a' <= ch && ch <= 'z')
        {
            [result appendFormat:@"%C",(char)ch];
        }
        else if ('0' <= ch && ch<='9')
        {
            [result appendFormat:@"%C",(char)ch];
        }
        else if (ch == '-' || ch == '_'
                 || ch == '.' || ch == '!'
                 || ch == '~' || ch == '*'
                 || ch == '\'' || ch == '('
                 || ch == ')')
        {
            [result appendFormat:@"%C",(char)ch];
        }
        else if (ch <= 0x007F)
        {
            [result appendFormat:@"%%",'%'];
            [result appendString:[hex objectAtIndex:ch]];
        }
        else
        {
            [result appendFormat:@"%%",'%'];
            [result appendFormat:@"%C",'u'];
            [result appendString:[hex objectAtIndex:ch>>8]];
            [result appendString:[hex objectAtIndex:0x00FF & ch]];
        }
    }
    return result;
}
//对特殊字符进行编辑

+(NSString*)encodeString:(NSString*)unencodedString{
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}


+ (NSString *) compareCurrentTime:(NSDate*) compareDate{
    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分前",temp];
    }else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小前",temp];
    }else if((temp = temp/24) <30){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }else if((temp = temp/30) <12){
        result = [NSString stringWithFormat:@"%ld月前",temp];
    }else{
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
    }
    return  result;
}

+ (NSString *) formatStringSplit:(NSString *) str space:(NSInteger)space place:(NSString *)place{
    NSMutableString *temp = [NSMutableString string];
    if (place == nil || [place isEqualToString:@""] || str.length <= space) {
        return str;
    }
    for (int i = 0; i < str.length ; i += space) {
        if (i + space >= str.length) {
            [temp appendString:[str substringWithRange:NSMakeRange(i, str.length - i)]];
            break;
        }
        [temp appendString:[str substringWithRange:NSMakeRange(i, space)]];
        [temp appendString:place];
    }
    return temp;
}

+ (NSString *) getRand{
    int rand = arc4random() % 1000000 + 1000000;
    return [NSString stringWithFormat:@"%d", rand];
}

+ (NSString *) getUUID{
    NSString *device_uuid = [self getCacheData:@"Device_UUID"];
    if (device_uuid && ![device_uuid isEqualToString:@""]) {
        return device_uuid;
    }
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    result = [result stringByReplacingOccurrencesOfString:@"-" withString:@""];
    [self saveCacheData:result key:@"Device_UUID"];
    return result;
}

+ (UIColor *)getColor:(NSString *)hexColor{
    return [UIColor colorFromHexString:hexColor];
}

+ (NSString *) transformDateFromString:(NSString *)datestr andFormat:(NSString *)fromformat toFormat:(NSString *)toformat{
    NSDateFormatter *fromFormatter= [[NSDateFormatter alloc] init];
    [fromFormatter setDateFormat:fromformat];
    NSDate*fromDate = [fromFormatter dateFromString:datestr];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:toformat];
    NSString *currentDateStr = [dateFormatter stringFromDate:fromDate];
    return currentDateStr;
}

+ (NSString *)formatHtml:(NSString *)html{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO){
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    return html;
}

+ (void)HttpRequestTask:(BOOL)isPost withUrl:(NSString *)url withData:(NSDictionary *)parameters notifyError:(BOOL)notifyError onSuccess:(void (^)(BaseModel * model))success onError:(void (^)(BaseModel *))error{
    [CClass HttpRequestTask:isPost withUrl:url withData:parameters notifyError:notifyError onSuccess:success onError:error progress:nil];
}

+ (void)HttpRequestTask:(BOOL)isPost withUrl:(NSString *)url withData:(NSDictionary *)parameters notifyError:(BOOL)notifyError onSuccess:(void (^)(BaseModel * model))success onError:(void (^)(BaseModel *))error progress:(void (^)(float))progress{
    
    static AFHTTPSessionManager *manager;
    if (manager == nil) {
        manager = [AFHTTPSessionManager manager];
    }
    __block typeof(error) g_error = error;
    
    void (^t_progress)(NSProgress * _Nonnull) = ^(NSProgress * _Nonnull downloadProgress){
        if (progress) {
            
        }
    };
    
    void (^t_success)(NSURLSessionDataTask * _Nonnull, id  _Nullable) = ^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        if (!success) return;
        
        NSError *error = nil;
        BaseModel *model = [[BaseModel alloc] initWithDictionary:responseObject error:&error];
        
//       echo(model.B_data);
                echo(responseObject);
        
        
        if (error != nil) {
#ifdef C_DEBUG
            [self showMessage:@"Model Error"];
#endif
            return ;
        }
        if ([model.B_code isEqualToString:@"200"]) {
            success(model);
        }else if([model.B_code isEqualToString:@"800"]){
            if ([CClass hasCacheData:NSUD_Token]) {
                
                [self showMessage:model.B_msg];
                double delayInSeconds = 1;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    //重新登录
                     [CClass clearCacheData:@[NSUD_Token, NSUD_UUID,NSUD_state,NSUD_Mobile,NSUD_HeadImg,NSUD_City,NSUD_Province,NSUD_Mobile,NSUD_Name,NSUD_state,NSUD_Uuid]];
                    UINavigationController *viewcontroller = (UINavigationController *)[[[UIApplication sharedApplication]keyWindow] rootViewController];
                    [viewcontroller popToRootViewControllerAnimated:NO];
                    [[(BaseViewController *) viewcontroller.viewControllers.firstObject mainTabBar] setShowIndex:0];
                    [(AppDelegate *)[[UIApplication sharedApplication] delegate] login];
                    
                });
                //不登录的时候不推送
                [(AppDelegate *)[[UIApplication sharedApplication] delegate] unRegisterPush];
            }else if(notifyError){
                [self showMessage:model.B_msg];
                id viewcontroller = [[[UIApplication sharedApplication]keyWindow] rootViewController];
                [(UINavigationController *)viewcontroller popToRootViewControllerAnimated:YES];
                [(AppDelegate *)[[UIApplication sharedApplication] delegate] login];
            }else{
                [self showMessage:model.B_msg];
                [(AppDelegate *)[[UIApplication sharedApplication] delegate] login];
            }
            
            
            
            if (g_error) {
                g_error(model);
            }
        }else{
            if (notifyError) {
                [self showMessage:model.B_msg];
            }
            if (g_error) {
                g_error(model);
            }
        }
//        [[LoadingView shareLoading] stopAnimating];
    };
    
    void (^t_error)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull) = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        #ifdef C_DEBUG
        if(error.code != -1016)
            [self showMessage:@"服务器升级中，请稍后再试"];
        if (error.code == -1009) {
            [self showMessage:[NSString stringWithFormat:@"网络异常, 请稍后再试"]];
        }
        

#endif
        if (g_error) {
            g_error(nil);
        }
//        [[LoadingView shareLoading] stopAnimating];
    };
    
    if (![url hasPrefix:@"http"]) {
        url = [Constants apiWithKey:url];
    }
    
    NSDictionary *newparam = [self remakeParam:parameters];
#ifdef C_DEBUG
    echo(url);
    echo(newparam);
#endif
    [manager POST:url parameters:newparam progress:nil success:t_success failure:t_error];
    return;
    if (isPost) {
        void (^t_formdata)(id<AFMultipartFormData>  _Nonnull) = ^(id<AFMultipartFormData>  _Nonnull formData) {
            
        };
        
        [manager POST:url parameters:newparam progress:nil success:t_success failure:t_error];
        
    }else{
        [manager GET:url parameters:newparam progress:t_progress success:t_success failure:t_error];
    }
}

+ (NSDictionary *)remakeParam:(NSDictionary *)parameters{
    NSString *token = [self getCacheData:NSUD_Token];
    NSMutableDictionary *newparam = [NSMutableDictionary dictionaryWithDictionary:parameters ? parameters : @{}];
    [newparam setObject:@"20" forKey:@"device"];
    [newparam setObject:@"app" forKey:@"client"];
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    NSString* versionNum =[infoDict objectForKey:@"CFBundleVersion"];
    [newparam setObject:versionNum forKey:@"version"];
    if (token != nil && ![token isEqualToString:@""]) {
        [newparam setObject:token forKey:@"authtoken"];
    }
    return newparam;
}
//截取图片大小
+ (UIImage *)squareImageFromImage:(UIImage *)image scaledToSize:(CGFloat)newSize {
    CGAffineTransform scaleTransform;
    CGPoint origin;
    
    if (image.size.width > image.size.height) {
        //image原始高度为200，缩放image的高度为400pixels，所以缩放比率为2
        CGFloat scaleRatio = newSize / image.size.height;
        scaleTransform = CGAffineTransformMakeScale(scaleRatio, scaleRatio);
        //设置绘制原始图片的画笔坐标为CGPoint(-100, 0)pixels
        origin = CGPointMake(-(image.size.width - image.size.height) / 2.0f, 0);
    } else {
        CGFloat scaleRatio = newSize / image.size.width;
        scaleTransform = CGAffineTransformMakeScale(scaleRatio, scaleRatio);
        
        origin = CGPointMake(0, -(image.size.height - image.size.width) / 2.0f);
    }
    
    CGSize size = CGSizeMake(newSize, newSize);
    
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(size);
    }
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    //将image原始图片(400x200)pixels缩放为(800x400)pixels
    CGContextConcatCTM(context, scaleTransform);
    //origin也会从原始(-100, 0)缩放到(-200, 0)
    [image drawAtPoint:origin];
    
    //获取缩放后剪切的image图片
    image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark 根据宽等比压缩图片
+ (UIImage *)resizeImage:(UIImage *)image ByWidth:(float) width{
    CGSize size = CGSizeMake(width, 0);
    return [CClass resizeImage:image FromSize:size];
}
//把图片变成固定的长宽
+ (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize

{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return reSizeImage;
    
}
#pragma mark 等比压缩图片
+ (UIImage *)resizeImage:(UIImage *)image FromSize:(CGSize) size{
    if (!image) {
        return nil;
    }
    float bl = MIN(size.width / image.size.width, size.height / image.size.height);
    if (bl == 0) {
        bl = MAX(size.width / image.size.width, size.height / image.size.height);
    }
    if (image.size.width <= size.width && image.size.height <= size.height) {
        return image;
    }else if(image.size.width > size.width && image.size.height > size.height){
        size.width = image.size.width * bl;
        size.height = image.size.height * bl;
    }else if(image.size.width > size.width && size.width > 0){
        size.height = image.size.height * bl;
    }else if(image.size.height > size.height && size.height > 0){
        size.width = image.size.width * bl;
    }else{
        return image;
    }
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(size);
    }
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}
+ (NSData *)compressImageQuality:(UIImage *)image
{
    CGFloat compression = 0.5;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    echo(([NSString stringWithFormat:@"source image size:%.2fkb", imageData.length / 1024.0]));

    while (imageData.length > IMAGE_MAX_SIZE && compression > 0.1) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    echo(([NSString stringWithFormat:@"final image size:%.2fkb", imageData.length / 1024.0]));

    return imageData;
}
+ (void)showMessage:(NSString *)message  completion:(void (^)())completion{
    
    if (message == nil || [message isEqualToString:@""]) {
        return;
    }
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *showview = [[UIView alloc] init];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [showview setBackgroundColor:[UIColor colorFromHexString:@"7a7a7a"]];
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc] init];
    
    CGSize labelsize = [message sizeWithFont:F(15) constrainedToSize:CGSizeMake(220, 900)];
    label.frame = CGRectMake(30, 18, labelsize.width, labelsize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor clearColor];
    label.font = F(15);
    [label setNumberOfLines:0];
    [label setTextAlignment:NSTextAlignmentCenter];
    [showview addSubview:label];
    
    showview.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - labelsize.width - 60) / 2, [UIScreen mainScreen].bounds.size.height / 2 - 48, labelsize.width + 60, labelsize.height + 32);
    [UIView animateWithDuration:1 delay:1 options:UIViewAnimationOptionCurveEaseOut animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        
        //介绍之后
        if (completion) {
            completion();
            
        }else
        {
        }
        [showview removeFromSuperview];
        
    }];
}
+ (void)showLittleTimeMessage:(NSString *)message  completion:(void (^)())completion{
    
    if (message == nil || [message isEqualToString:@""]) {
        return;
    }
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *showview = [[UIView alloc] init];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [showview setBackgroundColor:[UIColor colorFromHexString:@"7a7a7a"]];
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc] init];
    
    CGSize labelsize = [message sizeWithFont:F(15) constrainedToSize:CGSizeMake(220, 900)];
    label.frame = CGRectMake(30, 18, labelsize.width, labelsize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor clearColor];
    label.font = F(15);
    [label setNumberOfLines:0];
    [label setTextAlignment:NSTextAlignmentCenter];
    [showview addSubview:label];
    
    showview.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - labelsize.width - 60) / 2, [UIScreen mainScreen].bounds.size.height / 2 - 48, labelsize.width + 60, labelsize.height + 32);
    [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        
        //介绍之后
        if (completion) {
            completion();
            
        }else
        {
        }
        [showview removeFromSuperview];
        
    }];
}
+ (void)showMessage:(NSString *)message
{
    
    if (message == nil || [message isEqualToString:@""]) {
        return;
    }
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *showview = [[UIView alloc] init];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [showview setBackgroundColor:[UIColor colorFromHexString:@"7a7a7a"]];
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc] init];
    CGSize labelsize = [message sizeWithFont:F(15) constrainedToSize:CGSizeMake(220, 900)];
    label.frame = CGRectMake(30, 18, labelsize.width, labelsize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor clearColor];
    label.font = F(15);
    [label setNumberOfLines:0];
    [label setTextAlignment:NSTextAlignmentCenter];
    [showview addSubview:label];
    
    showview.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - labelsize.width - 60) / 2, [UIScreen mainScreen].bounds.size.height / 2 - 48, labelsize.width + 60, labelsize.height + 32);
    [UIView animateWithDuration:1 delay:1 options:UIViewAnimationOptionCurveEaseOut animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        
        [showview removeFromSuperview];
        
    }];
}

+ (void) showAlertTitle:(NSString *) title  hidden:(BOOL)state context:(NSString*)context oneBtn:(NSString*)oneBtnTitle twoBtn:(NSString*)twoBtnTitle handler:(void (^)(void))oneBtn handler:(void (^)(void))twoBtn
{
    AlertWindow *alert = [AlertWindow sharedInstance];
    alert.title = title;
    alert.context =context;
    alert.oneBtnTitle =oneBtnTitle;
    alert.twoBtnTitle =twoBtnTitle;
    alert.showCancleBtn = !state;
    [alert setAfterOneBtn:oneBtn];
    [alert setAfterTwoBtn:twoBtn];
    [alert show];
    [alert becomeFirstResponder];
}


+(NSString*)replace:(NSString*)phone
{
    NSRange range1 = {0, 3};
    NSRange range2 = {3, 4};
    NSRange range3 = {7, 4};
    
    
    
    NSString *result = [NSString stringWithFormat:@"%@-%@-%@",[phone substringWithRange:range1],[phone substringWithRange:range2],[phone substringWithRange:range3]];
    return result;
}

+ (void)openImagePicker:(id)controller sourceType:(UIImagePickerControllerSourceType)sourceType allowsEditing:(BOOL)allowsEditing
{
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [CClass showMessage:@"该设备不支持"];
        return;
    }
    UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
    [self setImagePickerStyle:imgPicker];
    [imgPicker setSourceType:sourceType];
    [imgPicker setDelegate:controller];
    [imgPicker setAllowsEditing:allowsEditing];
    [controller presentViewController:imgPicker animated:YES completion:^{}];
}
+ (void)setImagePickerStyle:(UIImagePickerController *)controller
{
    
    // 修复导航栏高度问题
    controller.navigationBar.clipsToBounds = YES;
    
}
+ (void)deleteFileWithPath:(NSString *)path
{
    NSError *error = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        echo(@"存在");
    }
    if([fileManager removeItemAtPath:path error:&error])
    {
        echo(([NSString stringWithFormat:@"删除失败的原因----%@",error]));

        
    }
    
}
+ (UINavigationController*)getLastNavigationController
{
    UITabBarController *barController = (UITabBarController*)[UIApplication sharedApplication].windows[0].rootViewController;
    return barController.viewControllers[barController.selectedIndex];
}
///虚线
+ (void)layoutDottedLineWithoriginY:(float)originY WithAddSubview:(UIView *)view
{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
    // 设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:C(@"d4d4d4").CGColor];
    // 3.0f设置虚线的宽度
    [shapeLayer setLineWidth:0.5f];
    [shapeLayer setLineJoin:kCALineJoinRound];
    // 3=线的宽度 1=每条线的间距
    [shapeLayer setLineDashPattern:
     [NSArray arrayWithObjects:[NSNumber numberWithInt:3],
      [NSNumber numberWithInt:1],nil]];
    // Setup the path
    CGMutablePathRef path = CGPathCreateMutable();
    // 0,10代表初始坐标的x，y
    // 320,10代表初始坐标的x，y
    CGPathMoveToPoint(path, NULL, 15, originY-0.5);
    CGPathAddLineToPoint(path, NULL, WindowWidth-15,originY);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    // 可以把self改成任何你想要的UIView, 下图演示就是放到UITableViewCell中的
    [[view layer] addSublayer:shapeLayer];
    
}
//禁止输入表情
+ (NSString *)disable_emoji:(NSString *)text
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text
                                                               options:0
                                                                 range:NSMakeRange(0, [text length])
                                                          withTemplate:@""];
    return modifiedString;
}
//判断NSString字符串是否包含emoji表情
//判断是否输入了emoji 表情
+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}
//iOS 判断是否开启定位
+ (BOOL)isLocationServiceOpen {
    if ([ CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        return NO;
    } else
        return YES;
}
@end
